﻿using System;
using System.Web;
using MVCFoto.HttpHandler.Configuration;

namespace MVCFoto.HttpHandler
{
    public class ImageHandler: IHttpHandler
    {
        public ImageHandler()
        {
    
        }

        public void ProcessRequest(HttpContext context)
        {
            Configuration.ImageHandlerConfigSection config = (Configuration.ImageHandlerConfigSection)System.Configuration.ConfigurationManager.GetSection("ImageHandler");
            if (config.Enable)
            {
                if (IsImage(config.Redirect))
                {
                    //请求的为显示盗链的图片
                    if (context.Request.FilePath.ToLower().EndsWith(config.Redirect.Replace("~", "").ToLower()))
                        RedirectToOrigin(context);
                }


                if (IsAllow(config, context))
                {
                    RedirectToOrigin(context);
                }
                else
                {
                    context.Response.Redirect(config.Redirect);
                  /*  if (IsImage(config.Redirect))
                    {//图片
                        context.Response.Clear();
                        context.Response.ContentType = string.Format("image/{0}", config.Redirect.Substring(config.Redirect.LastIndexOf(".") + 1));
                        context.Response.WriteFile(config.Redirect);
                        context.Response.End();
                    }
                    else
                    {//url
                        context.Response.Redirect(config.Redirect);
                    }
                   * */
                }
                   
            }
            else
                RedirectToOrigin(context);   
        }
        bool IsImage(string path)
        {
            string redirectExt = path.ToLower().Substring(path.LastIndexOf(".") + 1);
            if ("jpg,gif,png".IndexOf(redirectExt) >= 0) return true;
            else return false;
        }
        bool IsAllow(Configuration.ImageHandlerConfigSection config, HttpContext context)
        {
            //忽略redirect提示图片
            
            string refHost = "";
            if (context.Request.UrlReferrer != null)
                refHost = context.Request.UrlReferrer.Host.ToLower();
            else
                //直接访问
                return config.AllowDirectAccess;
                
            string curHost = context.Request.Url.Host.ToLower();
            //本域
            if (curHost == refHost) return true;

            if (config.AllowDomains.Count > 0)
            {
                foreach (DomainElement domain in config.AllowDomains)
                { 
                    string d = domain.Domain.Replace("*","");
                    if (d.StartsWith("."))
                    {//根域匹配
                        d = d.Substring(1);
                        if (refHost.EndsWith(d))
                            return true;
                    }
                    else
                    {//完全匹配
                        if (refHost == d)
                            return true;
                    }
                }
                return false;
            }
            //禁止的域名
            if (config.DenyDomains.Count > 0)
            {
                foreach (DomainElement domain in config.DenyDomains)
                {
                    string d = domain.Domain.Replace("*", "");
                    if (d.StartsWith("."))
                    {//根域匹配
                        d = d.Substring(1);
                        if (refHost.EndsWith(d))
                            return false;
                    }
                    else
                    {//完全匹配
                        if (refHost == d)
                            return false;
                    }
                   
                }
                return true;
            }

            if (string.IsNullOrEmpty(refHost) || refHost != curHost)
            {
                return false;
            }
            else
                return true;
        }
        /// <summary>
        /// 返回原请求图片
        /// </summary>
        /// <param name="context"></param>
        public void RedirectToOrigin(HttpContext context)
        {
            context.Response.Clear();
            context.Response.ContentType = string.Format("image/{0}", context.Request.FilePath.Substring(context.Request.FilePath.LastIndexOf(".") + 1));
            context.Response.WriteFile(context.Request.FilePath);
            context.Response.End();
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}
